package com.iot.ic.controller;

import com.iot.ic.base.BaseController;
import com.iot.ic.common.Response;
import com.iot.ic.common.ReturnCode;
import com.iot.ic.model.RefereeInfo;
import com.iot.ic.model.ScenesResult;
import com.iot.ic.service.LogService;
import com.iot.ic.service.RefereeService;
import com.iot.ic.service.ScenesResultService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by xiuge on 2017/7/6.
 */
@RestController
@Api(description = "场景比赛成绩记录相关接口")
public class ScenesResultController extends BaseController{

    @Autowired
    private ScenesResultService scenesResultService;
    
    @Autowired
	private RefereeService refereeService;
    
	@Autowired
	private LogService logService;

    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;

    @ApiOperation(value = "获取最近count条场景得分记录", notes = "count是获取条数，不带此参数可以获取全部记录。teamId是参赛队Id，不带此参数可以获取全部队伍的场景得分")
    @GetMapping(value = "/scenesResults")
    public Response getScenesResultList(@RequestParam(value = "count", required = false, defaultValue = "99999") Integer count,
                                        @RequestParam(value = "teamId", required = false, defaultValue = "-1") Integer teamId,
                                        @RequestParam(value = "startTime", required = false) String startTime,
                                        @RequestParam(value = "endTime", required = false) String endTime) {
        Response response = new Response();
        List<Map<String, Object>> list = scenesResultService.getScenesReslutList(count,teamId, startTime, endTime);
        response.setResult(list);
        return response;
    }

    @ApiOperation(value = "获取最近count条场景得分记录，websocket请求", notes = "count是获取条数，不带此参数可以获取全部记录。teamId是参赛队Id，不带此参数可以获取全部队伍的场景得分")
    @MessageMapping("/scenesResultsSocket")
    @SendToUser("/scenes/results")
    public void getScenesResultListSocket(
            @Header(value = "user", required = false, defaultValue = "") String adminId,
            @Header(value = "count", required = false, defaultValue = "99999") Integer count,
            @Header(value = "teamId", required = false, defaultValue = "-1") Integer teamId,
            @Header(value = "startTime", required = false) String startTime,
            @Header(value = "endTime", required = false) String endTime
    ) {
        Response response = new Response();
        List<Map<String, Object>> list = scenesResultService.getScenesReslutList(count,teamId, startTime, endTime);
        response.setResult(list);

        simpMessagingTemplate.convertAndSendToUser(adminId, "/scenes/results", response);
    }

    /**
     * 提交场景成绩
     *
     * @param userId
     * @param scenesResult
     * @return
     */
    @ApiOperation(value = "提交场景成绩", notes = "")
    @ResponseBody
    @RequestMapping(value = "/users/{userId}/scenes/result", method = RequestMethod.POST)
    public Response postScenesResult(@PathVariable("userId") int userId,
                                     @Valid @RequestBody ScenesResult scenesResult) {
        Response response = new Response();
        Map<String, Object> stadiumTeamInfoMap = scenesResultService.getStadiumTeamByScenesResult(scenesResult.getScenesResultId());
        String stadiumName = stadiumTeamInfoMap.get("stadiumName").toString();
        String scenesName = stadiumTeamInfoMap.get("scenesName").toString();
        String teamName = stadiumTeamInfoMap.get("teamName").toString();
        RefereeInfo user = refereeService.getRefereeInfo(userId);
		logService.addLogs(user.getRefereeNo(), user.getRefereeName(), new Date(), "提交场景成绩", "提交"+teamName+"车队在"+stadiumName+"场景"+scenesName+"的成绩");
        Map<String, Object> resultMap = scenesResultService.postScenesResult(scenesResult);
        if (Integer.parseInt(resultMap.get("result").toString()) == 1) {
            response.setInfos(ReturnCode.No_PostScenesResultOK);
            response.setResult(resultMap);
        } else {
            response.setInfos(ReturnCode.Err_PostScenesResultFailor);
        }
        return response;
    }


    /**
     * 根据车队和赛道获得场景成绩列表
     * @param userId
     * @param teamId
     * @param stadiumId
     * @return
     */
    @ApiOperation(value = "根据车队和赛道获得场景成绩列表", notes = "")
    @ResponseBody
    @RequestMapping(value = "/users/{userId}/team/{teamId}/stadium/{stadiumId}/scenesResults", method = RequestMethod.GET)
    public Response listScenesResultByTeamAndStadium(@PathVariable("userId") int userId,
                                                     @PathVariable("teamId") int teamId,
                                                     @PathVariable("stadiumId") int stadiumId) {
        Response response = new Response();
        ScenesResult scenesResult = new ScenesResult();
        scenesResult.setTeamId(teamId);
        scenesResult.setStadiumId(stadiumId);
        List<ScenesResult> resultMap = scenesResultService.listScenesResultByStadiumAndTeam(scenesResult);
        response.setResult(resultMap);

        return response;
    }

    @ApiOperation(value = "获取场景的违规和人工干预详情", notes = "")
    @GetMapping("/users/{userId}/scenes/{scenesId}/teams/{teamId}/scenesResults")
    public Response getScenesWithIllegalAndManual(@PathVariable("userId")int userId,
                                                  @PathVariable("scenesId")int scenesId,
                                                  @PathVariable("teamId")int teamId){
        Response response = new Response();
        List<ScenesResult>scenesResultList=scenesResultService.getScenesResultWithIllegalAndManual(scenesId,teamId);
        response.setResult(scenesResultList);
        return response;
    }

    @ApiOperation(value = "获取某个场景得分的违规和人工干预详情", notes = "")
    @GetMapping("/users/{userId}/scenesResults/{scenesResultId}")
    public Response getScenesWithIllegalAndManual(@PathVariable("userId")int userId,
                                                  @PathVariable("scenesResultId")int scenesResultId){
        Response response = new Response();
        ScenesResult scenesResult=scenesResultService.getScenesResultDetail(scenesResultId);
        response.setResult(scenesResult);
        return response;
    }

}
